# -*- coding: utf-8 -*-

import logging

from django.conf import settings
from django.contrib.auth.models import User
from django.core import serializers
from django.db.models import Q, QuerySet
from django.http.request import HttpRequest, QueryDict
from django.http.response import HttpResponse, JsonResponse, FileResponse, HttpResponseServerError
from django.views import View
from django.views.decorators.cache import cache_page, cache_control
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from app_module.messages import default_response, failure_response

logger = logging.getLogger(__name__)


class ClassView(View):

    def get(self, request: HttpRequest):
        # url参数：GET
        query_dict: QueryDict = request.GET
        keywords = query_dict.get('keywords', default='')
        queryset: QuerySet = User.objects.filter(Q(username__startswith=keywords))
        # model序列化，出现多余字段问题
        string: str = serializers.serialize('json', queryset)
        return HttpResponse(content=string.encode(encoding=settings.DEFAULT_CHARSET),
                            content_type='application/json')

        # 参数data非dict类型，参数safe=False，json.loads解决重复引号问题
        # return JsonResponse(json.loads(string), safe=False)

    def post(self, request):
        query_dict: QueryDict = request.GET
        filepath = query_dict.get('filepath')
        filename = query_dict.get('filename')
        if filepath is not None and filename is not None:
            return FileResponse(open(filepath, "rb"), as_attachment=True, filename=filename)
        else:
            return HttpResponseServerError(content=b'filepath is None or filename is None')


@require_POST
def post_json(request):
    if request.content_type == 'application/json':
        logger.info('request:' + str(request.body))
    return JsonResponse(default_response())


@require_POST
def post_form(request: HttpRequest):
    if request.content_type == 'multipart/form-data':
        value = request.POST.get('key', default='empty')
        logger.info('value:%s', value)
        if len(request.FILES) == 0:
            return JsonResponse(failure_response('form-data key not file'))
        file = request.FILES.get('file')
        for chunk in file.chunks():
            logger.info('chunk:%s', chunk.decode())
            pass
        pass

    return JsonResponse(default_response())


@cache_page(1)
def cache0(request):
    logger.info('cache0')
    return JsonResponse(default_response())


@cache_control(private=True)
def cache1(request):
    logger.info('cache1')
    return JsonResponse(default_response())


def cache2(request):
    logger.info('cache2')
    return JsonResponse(default_response())
